import React, { Component } from 'react'
import { Switch, Route, withRouter, Redirect } from 'react-router-dom'
import { Layout } from 'antd'
import { routes } from '../../router/routes'
import { connect } from 'react-redux'

const { Content } = Layout

class Main extends Component {
    componentDidMount () {
        // console.log('routes', this.setRoutes(routes))
    }

    componentDidUpdate (prevProps, prevState, snapshot) {
        let { location: { pathname: lastPath } } = prevProps
        let { location: { pathname: currentPath } } = this.props
        if (lastPath !== currentPath) {
            this.props.auto(currentPath)
        }
    }

    setRoutes (routes) {
        let routeArray = []
        routes.forEach((item) => {
            if (item.redirect) {
                routeArray.push(<Redirect key={item.path} from={item.path} to={item.redirect} exact></Redirect>)
            }
            if (!item.children) {
                routeArray.push(<Route key={item.path} path={item.path} component={item.component} exact></Route>)
            } else {
                routeArray.push(<Route key={item.path} path={item.path} component={item.component} exact></Route>)
                routeArray = routeArray.concat(this.setRoutes(item.children))
            }
        })
        return routeArray
    }

    render () {
        return (
            <Content
                className="site-layout-background content"
                style={{
                    margin: '0 16px 24px 16px',
                    padding: 24,
                    minHeight: 280,
                    overflow: 'hidden'
                }}>
                <Switch>
                    {this.setRoutes(routes)}
                    <Redirect from="*" to="/none"></Redirect>
                </Switch>
            </Content>)
    }
}

export default connect((state) => {
    return {
        open: state.getIn(['slide', 'open'])
    }
}, (dispatch) => {
    return {
        auto: (key) => {
            dispatch({ type: 'auto', value: key })
        }
    }
})(withRouter(Main))
